﻿using OvenParameterForm.Device;
using OvenParameterForm.Model;
using OvenParameterForm.UserInterface;
using OvenParameterForm.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace OvenParameterForm.CustomizeControl
{
    public partial class Tc_OvenRun : UserControl, IUpdateData
    {
        public Oven oven;
        UILineOption option = new UILineOption();
        private string path = Application.StartupPath + "\\系统配置\\";
        internal ovenPLCAddress ovenPLCaddress = new ovenPLCAddress();
        private DateTime dtStartTechnics;
        private double th1Temperature;
        private double th2Temperature;
        private double th3Temperature;
        private double th4Temperature;
        private double vaccumValue;
        private SqlSugarClientHelp<OvenTemperatureChart> sqlChartDAL = new SqlSugarClientHelp<OvenTemperatureChart>();
        private System.Threading.Timer uptimer, UIuptimer;
        private int chartRecordinternal = 1000;
        string str1, str2, str3;
        public Tc_OvenRun(string ovenname)
        {
            InitializeComponent();
            this.Name = "tpg_" + ovenname;//设置界面名称
            oven = new Oven(ovenname);//创建烘箱设备
            XDocument xdo = XDocument.Load(path + ovenname + ".xml");//打开该烘箱配置文件，并加载地址
            ovenPLCaddress = PublicFunc.XMLToClass<ovenPLCAddress>(xdo.Root.Element(ovenPLCaddress.GetType().Name), ovenPLCaddress);
            LoadPage();//加载页面，主要是曲线绘制初始化
            oven.TechnicsStartAndStopAction = (bool state) =>
            {

                if (this.InvokeRequired)
                {
                    // if(state)
                    //tim_update.Start();
                    // else
                    //     tim_update.Stop();
                    UIuptimer.Change(state ? 0 : -1, chartRecordinternal);
                }
                else
                {
                    UIuptimer.Change(state ? 0 : -1, chartRecordinternal);
                    //this.Invoke(new Action(() => {
                    //    if (state)
                    //        tim_update.Start();
                    //    else
                    //        tim_update.Stop();
                    //}));
                }


            };//设置收到流程结束委托要做的事
            oven.ReceiveTechnicsRunInfoAction = (string str) =>
            {

                if (lb_ovenRunInfo.InvokeRequired)
                    this.Invoke(new Action(() => { lb_ovenRunInfo.Text = str; }));
            };//设置烘箱运行中收到信息要处理的事
            uptimer = new System.Threading.Timer((object o) => { UpdateData(); }, null, -1, 1000);//启动计时器刷新
            UIuptimer = new System.Threading.Timer(UIChartUpdate, null, -1, 1000);//启动计时器刷新
        }
        private void LoadPage()
        {
            option.ToolTip.Visible = true;
            option.Title = new UITitle();
            option.Title.Text = "实时数据曲线";
            option.Title.SubText = "温度与真空度曲线";

            option.XAxisType = UIAxisType.DateTime;
            UILineSeries series1 = option.AddSeries(new UILineSeries("层1温度曲线", Color.Red));
            UILineSeries series2 = option.AddSeries(new UILineSeries("层2温度曲线", Color.Green));
            UILineSeries series3 = option.AddSeries(new UILineSeries("层3温度曲线", Color.Orange));
            UILineSeries series4 = option.AddSeries(new UILineSeries("层4温度曲线", Color.Blue));
            UILineSeries series5 = option.AddSeries(new UILineSeries("真空度", Color.Purple, true));

            series1.Symbol = UILinePointSymbol.None;
            series1.SymbolSize = 3;
            series1.SymbolLineWidth = 2;
            series1.Smooth = true;
            series1.Color = Color.Red;
            series1.ShowLine = true;

            series2.Symbol = UILinePointSymbol.None;
            series2.SymbolSize = 3;
            series2.SymbolLineWidth = 2;
            series2.Smooth = true;
            series2.Color = Color.Green;
            series2.ShowLine = true;

            series3.Symbol = UILinePointSymbol.None;
            series3.SymbolSize = 3;
            series3.SymbolLineWidth = 2;
            series3.Smooth = true;
            series3.Color = Color.Orange;
            series3.ShowLine = true;

            series4.Symbol = UILinePointSymbol.None;
            series4.SymbolSize = 3;
            series4.SymbolLineWidth = 2;
            series4.Smooth = true;
            series4.Color = Color.Blue;
            series4.ShowLine = true;

            series5.Symbol = UILinePointSymbol.None;
            series5.SymbolSize = 3;
            series5.SymbolLineWidth = 2;
            series5.Smooth = true;
            series5.Color = Color.Purple;
            series5.ShowLine = true;

            option.XAxis.Name = "时间";//横轴名称
            option.YAxis.Name = "摄氏度";//纵轴1名称
            option.Y2Axis.Name = "真空度";//纵轴2名称
            option.XAxis.AxisLabel.DateTimeFormat = "HH:mm:ss";
            option.XAxis.SetMinValue(DateTime.Parse("00:00:01"));
            uiLineChart1.SetOption(option);
        }

        /// <summary>
        /// 刷新数据函数
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void UpdateData()
        {
            th1Temperature = Convert.ToDouble(PLC.ReadData(ovenPLCaddress.层1温度地址)) / 10;
            th2Temperature = Convert.ToDouble(PLC.ReadData(ovenPLCaddress.层2温度地址)) / 10;
            th3Temperature = Convert.ToDouble(PLC.ReadData(ovenPLCaddress.层3温度地址)) / 10;
            th4Temperature = Convert.ToDouble(PLC.ReadData(ovenPLCaddress.层4温度地址)) / 10;
            str1 = PLC.InovanceAM400PLCRead(ovenPLCaddress.真空计整数地址, 16);
            str2 = PLC.InovanceAM400PLCRead(ovenPLCaddress.真空计小数地址, 16);
            str3 = PLC.InovanceAM400PLCRead(ovenPLCaddress.真空计指数地址, 16);
            vaccumValue = Convert.ToDouble(str1 + "." + str2) * Math.Pow(10, Convert.ToInt16(str3));
            btn_OvenStartTechnics.Invoke(new Action(() =>
            {
                if (this.InvokeRequired)
                {
                    btn_OvenStartTechnics.Enabled = oven.OvenState ? false : true;
                }
                else
                {
                    this.Invoke(new Action(() =>
                    {
                        btn_OvenStartTechnics.Enabled = oven.OvenState ? false : true;
                    }));
                }
            }));
            //   Console.WriteLine($"计时器状态{tim_update.Enabled}");
            Console.WriteLine($"烘箱状态:{this.Name}{oven.OvenState}");
        }
        /// <summary>
        /// 启动烘箱工艺
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OvenStartTechnics_Click(object sender, EventArgs e)
        {
            uiLineChart1.Option.Clear();
            LoadPage();
            Panel.Frm_chartSetting tempFrm = new Panel.Frm_chartSetting();
            tempFrm.sendInterval = (int n) => { chartRecordinternal = n; };
            tempFrm.ShowDialog();
            dtStartTechnics = DateTime.Now;
            //  tim_update.Start();
            oven.StartTechnics();
        }
        /// <summary>
        /// 停止烘箱工艺
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OvenStopTechnics_Click(object sender, EventArgs e)
        {
            oven.StopTechnics();
            //   tim_update.Stop();
        }
        /// <summary>
        /// 加载配方
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tc_OvenRun_Load(object sender, EventArgs e)
        {
            oven.OpenFormula(this.tbox_OvenFomula);
            uptimer.Change(0, 1000);
        }
        /// <summary>
        /// 计时器刷新函数，主要负责温度曲线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tim_update_Tick(object sender, EventArgs e)
        {
            UIChartUpdate(null);
        }
        private void UIChartUpdate(object o)
        {
            this.Invoke(new Action(() =>
            {
                TimeSpan ts = DateTime.Now.Subtract(dtStartTechnics);//以当前时间为时间间隔
                uiLineChart1.Option.AddData("层1温度曲线", DateTime.Parse(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds), th1Temperature);
                uiLineChart1.Option.AddData("层2温度曲线", DateTime.Parse(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds), th2Temperature);
                uiLineChart1.Option.AddData("层3温度曲线", DateTime.Parse(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds), th3Temperature);
                uiLineChart1.Option.AddData("层4温度曲线", DateTime.Parse(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds), th4Temperature);
                uiLineChart1.Option.AddData("真空度", DateTime.Parse(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds), vaccumValue);
                uiLineChart1.Refresh();

                sqlChartDAL.InsertData(new OvenTemperatureChart
                {
                    OvenName = this.Name.SplitLast("_"),
                    ChartName = dtStartTechnics.ToString(),
                    ChartXData = DateTime.Parse(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds),
                    ChartY1Data = th1Temperature,
                    ChartY2Data = th2Temperature,
                    ChartY3Data = th3Temperature,
                    ChartY4Data = th4Temperature,
                    ChartY5Data = vaccumValue
                });

            }));
        }
    }
}
